package com.trsj.lnsj.service.imp;

import java.security.SecureRandom;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.trsj.lnsj.common.DataResponse;
import com.trsj.lnsj.common.MsgStatus;
import com.trsj.lnsj.entity.OrderDTO;
import com.trsj.lnsj.entity.OrderRepo;
import com.trsj.lnsj.entity.UserDTO;
import com.trsj.lnsj.entity.UserRepo;
import com.trsj.lnsj.mapper.UserMapper;
import com.trsj.lnsj.service.IUserService;
import com.trsj.lnsj.util.JWTHelper;
import com.trsj.lnsj.util.ResponseHelper;
import com.trsj.lnsj.util.wechat.CommonUtil;
import com.trsj.lnsj.util.wechat.WechatPayConfig;

import io.swagger.client.model.RegisterUsers;
import io.swagger.client.model.User;

@Service
public class UserService implements IUserService {
    public static String alinotify = "/api/user/appAliPayNotify";
    public static String wechatNotify = "/api/user/wechatNotify";
    private Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRepo userRepo;
    @Autowired
    private Environment env;
    @Autowired
    private OrderRepo orderRepo;
    @Autowired
    private RedisService redisService;

//    private Map<String, Object> codeMap = new HashMap<String, Object>();

    @Override
    public DataResponse saveUserInfo(UserDTO user) {
        DataResponse resp = null;
        List<UserDTO> userList = userMapper.selectUserInfo(user);

        Map<String, String> accountMap = new HashMap<String, String>();
        if (CollectionUtils.isNotEmpty(userList)) {
            UserDTO userDb = userList.get(0);
            user.setId(userDb.getId());
        } else {
            // 注册环信账号
            user.setCreateBy("admin");
            user.setCreateDate(new Date().getTime());
            user.setUpdateBy("admin");
            user.setUpdateDate(new Date().getTime());
            user.setDeleteFlag("N");
            String happyNo = generateHappyNo();//随机生成快乐号
            user.setHappyNo(happyNo);
            user.setNickname(user.getMobilephone().substring(user.getMobilephone().length()-4, user.getMobilephone().length()));
            String easePwd = generateRndPwd();
            accountMap = registerHuanxin(happyNo, easePwd);
            if (MapUtils.isEmpty(accountMap)) {
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "用户环信账号注册不成功!");
                return resp;
            } else {
                user.setEasePwd(easePwd);
            }
        }
        if (redisService.get(user.getMobilephone()).replaceAll("\"", "").equals(user.getValidCode())) {//验证码验证正确
            try {
                userRepo.saveAndFlush(user); //注册用户信息
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
                if (null == user.getId()) {
                    registSuccessMsg(user.getMobilephone());//发送注册成功短信
                }
            } catch (Exception e) {
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
            }
        } else {
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "手机验证码不正确!");
        }
        return resp;
    }

    @Override
    public List<UserDTO> selectUserInfo(UserDTO user) {
        List<UserDTO> userList = userMapper.selectUserInfo(user);
        return userList;
    }

    @Override
    public DataResponse login(UserDTO user) {
        DataResponse resp = null;
        Map<String, String> accountMap = new HashMap<String, String>();
        //获取用户ID
        UserDTO userParam = new UserDTO();
        userParam.setMobilephone(user.getMobilephone());
        userParam.setHappyNo(user.getHappyNo());
        List<UserDTO> userList = userMapper.selectUserInfo(userParam);//查询是否注册
        Map<String,Object> claims = new HashMap<String,Object>();
        if (CollectionUtils.isNotEmpty(userList)) {
            claims.put("userid", userList.get(0).getId());
        }
        String token = JWTHelper.createJavaWebToken(claims, 24*60*60*1000, env.getProperty("jwt.token.signkey"));
        if (StringUtils.isBlank(user.getValidCode())) { // 没有通过验证码登录
            if (CollectionUtils.isEmpty(userList)) {
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "您还未注册!");
            } else {
                if (!user.getPassword().equals(userList.get(0).getPassword())) {
                    resp = ResponseHelper.getResponse(MsgStatus.PWD_VALID_FAIL);
                } else {
                    // 返回环信账号信息
                    if (StringUtils.isEmpty(userList.get(0).getEasePwd())) {
                        resp = ResponseHelper.getResponse(MsgStatus.EASE_FAILED, "还未注册环信账号!");
                        return resp;
                    } else {
                        accountMap.put("username", userList.get(0).getEaseAccount());
                        accountMap.put("password", userList.get(0).getEasePwd());
                        accountMap.put("token", token);
                        accountMap.put("id", userList.get(0).getId().toString());
                        accountMap.put("nickname", userList.get(0).getNickname());
                        accountMap.put("happyNo", userList.get(0).getHappyNo());
                        accountMap.put("headpic", userList.get(0).getHeadPic());
                        accountMap.put("signature", userList.get(0).getSignature());
                        accountMap.put("mobilephone", userList.get(0).getMobilephone());
                    }
                    //通过手机号或快乐号登录
                    resp = ResponseHelper.getSuccessResponse(accountMap);
                }
            }
        } else if (!redisService.exists(user.getMobilephone())) {
            resp = ResponseHelper.getResponse(MsgStatus.VALIDCODE_OVERDUE);
            return resp;
        } else if (StringUtils.isNotBlank(user.getValidCode())
                && redisService.get(user.getMobilephone()).replaceAll("\"", "").equals(user.getValidCode())) {
            if (CollectionUtils.isEmpty(userList) && StringUtils.isNotBlank(user.getPassword())) {
                logger.info("password={}", user.getPassword());
                user.setCreateBy("admin");
                user.setCreateDate(new Date().getTime());
                user.setUpdateBy("admin");
                user.setUpdateDate(new Date().getTime());
                user.setDeleteFlag("N");
                String happyNo = generateHappyNo();//随机生成快乐号
                user.setHappyNo(happyNo);
                user.setNickname(user.getMobilephone().substring(user.getMobilephone().length()-4, user.getMobilephone().length()));
                String easePwd = generateRndPwd();
                // 注册环信账号
                accountMap = registerHuanxin(happyNo, easePwd);
                if (MapUtils.isEmpty(accountMap)) {
                    resp = ResponseHelper.getResponse(MsgStatus.EASE_FAILED);
                    return resp;
                } else {
                    user.setEasePwd(easePwd);
                    user.setEaseAccount(happyNo);
                }
                try {
                    UserDTO resUser = userRepo.saveAndFlush(user); //注册用户信息
                    accountMap.put("token", token);
                    accountMap.put("id", resUser.getId().toString());
                    accountMap.put("nickname", resUser.getNickname());
                    accountMap.put("happyNo", resUser.getHappyNo());
                    accountMap.put("headpic", resUser.getHeadPic());
                    accountMap.put("signature", userList.get(0).getSignature());
                    accountMap.put("mobilephone", userList.get(0).getMobilephone());
                    resp = ResponseHelper.getSuccessResponse(accountMap);
                    if (null != resUser.getId()) {
                        registSuccessMsg(user.getMobilephone());//发送注册成功短信
                    }
                } catch (Exception e) {
                    resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
                }
                //resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "您还未注册!");
            } else if (CollectionUtils.isEmpty(userList) && StringUtils.isBlank(user.getPassword())) {
                resp = ResponseHelper.getResponse(MsgStatus.USER_NOT_EXIST);
            } else {
                // 返回环信账号信息
                if (StringUtils.isEmpty(userList.get(0).getEasePwd())) {
                    resp = ResponseHelper.getResponse(MsgStatus.EASE_FAILED, "还未注册环信账号!");
                } else {
                    accountMap.put("username", userList.get(0).getEaseAccount());
                    accountMap.put("password", userList.get(0).getEasePwd());
                    accountMap.put("token", token);
                    accountMap.put("id", userList.get(0).getId().toString());
                    accountMap.put("nickname", userList.get(0).getNickname());
                    accountMap.put("happyNo", userList.get(0).getHappyNo());
                    accountMap.put("headpic", userList.get(0).getHeadPic());
                    accountMap.put("signature", userList.get(0).getSignature());
                    accountMap.put("mobilephone", userList.get(0).getMobilephone());
                    resp = ResponseHelper.getSuccessResponse(accountMap);
                }
            }
        } else if (StringUtils.isNotBlank(user.getValidCode())
                && !redisService.get(user.getMobilephone()).replaceAll("\"", "").equals(user.getValidCode())) {
            resp = ResponseHelper.getResponse(MsgStatus.VALIDCODE_ERROR);
        }
        logger.info("sysvalidcode={},uservalidcode={}", redisService.get(user.getMobilephone()).replaceAll("\"", ""),user.getValidCode());
        logger.info("responseinfo={}", "msgCode="+resp.getMsgCode()+",message="+resp.getMessage()+",data="+resp.getData());
        return resp;
    }

    @Override
    public DataResponse sendMsgCode(String mobilephone, String type, HttpSession session) {
        // 短信应用SDK AppID
        int appid = Integer.valueOf(env.getProperty("shortmsg.appid")); // 1400开头
        // 短信应用SDK AppKey
        String appkey = env.getProperty("shortmsg.appkey");
        DataResponse response = null;
        // 单发短信
        try {
            if (redisService.exists(mobilephone)) {
                response = ResponseHelper.getResponse(MsgStatus.SMS_LIMITED);
                return response;
            }
            String validCode = "123456";//generateValidCode();
            String remindMsg = "";
            SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
            UserDTO user = new UserDTO();
            user.setMobilephone(mobilephone);
            List<UserDTO> userList = userMapper.selectUserInfo(user);
            //if (Constants.SENDMSG_TYPE_LOGIN.equals(type)) {
            String action = "login";
            if (CollectionUtils.isNotEmpty(userList)) {
                remindMsg = "你正在登录快乐，验证码" + validCode + "。泄露或转发可能导致账号被盗。";
            //} else if (Constants.SENDMSG_TYPE_REGIST.equals(type)) {
            } else {
                action = "regist";
                remindMsg = validCode + "快乐注册短信验证码，5分钟内有效";
            }
//            SmsSingleSenderResult result = ssender.send(0, "86", mobilephone, remindMsg, "", "");
//            logger.info("shortmsg_result={}", result);
//            if ("OK".equals(result.errMsg)) {
                redisService.set(mobilephone, validCode, 120*1000l);
                logger.warn("validCode={}", validCode);
                if ("regist".equals(action)) {
                    response = ResponseHelper.getSuccessResponse("action","regist");
                } else {
                    response = ResponseHelper.getResponse(MsgStatus.STATUS_OK,"短信发送成功");
                }
//            } else {
//                response = ResponseHelper.getResponse(MsgStatus.SMS_FAILED);
//            }
        } catch (Exception e) {
            response = ResponseHelper.getResponse(MsgStatus.SMS_FAILED);
        }
        return response;
    }

    private void registSuccessMsg(String mobilephone) {
        // 短信应用SDK AppID
        int appid = Integer.valueOf(env.getProperty("shortmsg.appid")); // 1400开头
        // 短信应用SDK AppKey
        String appkey = env.getProperty("shortmsg.appkey");
        SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
        try {
            SmsSingleSenderResult result = ssender.send(0, "86", mobilephone, "尊敬的用户，恭喜您，已成功注册快乐！", "", "");
            logger.info("shortmsg_result={}", result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成短信验证码
     * 
     * @return
     */
    private int generateValidCode() {
        int validCode = (int)((Math.random()*9+1)*100000);
        return validCode;
    }

    /**
     * 注册后申请环信账号
     */
    public Map<String, String> registerHuanxin(String username, String password) {
        Map<String, String> accountMap = new HashMap<String, String>();
        RegisterUsers users = new RegisterUsers();
        // 创建环信账号
        User payload = new User().username(username).password(password);
        users.add(payload);
        EasemobIMUsers ease = new EasemobIMUsers();
        // 注册环信账号
        Object result = ease.createNewIMUserSingle(users);
        JSONObject json;
        try {
            json = (JSONObject) JSONObject.parse(result.toString());
        } catch (Exception e) {
            logger.info(e.getMessage());
            return new HashMap<String, String>();
        }
        System.out.println(json.get("applicationName"));
        if ("happy-chat".equals(json.get("applicationName"))) {
            accountMap.put("username", username);
            accountMap.put("password", password);
            return accountMap;
        } else {
            return new HashMap<String, String>();
        }
    }

    // 生成随机数字和字母密码
    public String generateRndPwd() {
        String val = "";
        SecureRandom random = new SecureRandom();
        // length为几位密码
        for (int i = 0; i < 8; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            // 输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                // 输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    @Override
    public DataResponse alipay(float payAmount, String orderNo, HttpServletRequest request) {
        OrderDTO order = orderRepo.findOne(orderNo);
        if (null == order || order.getPayAmount() != payAmount) {
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "订单不存在或支付金额不匹配！");
        }
        String APP_ID=env.getProperty("alipay.appid");
        String APP_PRIVATE_KEY=env.getProperty("alipay.private_key");
        String CHARSET="UTF-8";
        String ALIPAY_PUBLIC_KEY=env.getProperty("alipay.public_key");
        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient(env.getProperty("alipay.gateway"), APP_ID, APP_PRIVATE_KEY, "json", CHARSET, ALIPAY_PUBLIC_KEY, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest payRequest = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
//        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//        model.setBody("参加有偿活动费用");
//        model.setSubject("快乐有偿活动");
//        model.setOutTradeNo(orderNo);
//        model.setTimeoutExpress("30m");
//        model.setProductCode("QUICK_MSECURITY_PAY");
//        //model.setSellerId(env.getProperty("alipay.seller_id"));
//        model.setGoodsType("0");
//        model.setTimeExpire("45m");
//        model.setTotalAmount(""+payAmount);
//        payRequest.setBizModel(model);
//        payRequest.setNotifyUrl(alinotify);
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody("参加有偿活动费用");
        model.setSubject("快乐有偿活动");
        model.setOutTradeNo(orderNo);
        model.setTimeoutExpress("30m");
        model.setTotalAmount(""+payAmount);
        model.setProductCode("QUICK_MSECURITY_PAY");
        payRequest.setBizModel(model);
        payRequest.setNotifyUrl(request.getRequestURL().toString().split("/api/")[0] + alinotify);
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            AlipayTradeAppPayResponse response = alipayClient.sdkExecute(payRequest);
            System.out.println(response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
            if (response.isSuccess()) {
                //userMapper.insertUserActivity(mobilephone,activityId);
                //return "app_id="+env.getProperty("alipay.appid")+"biz_content="+payRequest.getBizContent()+response.get
                OrderDTO orderDto = new OrderDTO();
                orderDto.setOrderId(orderNo);
                orderDto.setPayAmount(payAmount);
                orderRepo.saveAndFlush(orderDto);
                System.out.println("调用成功");
            } else {
                System.out.println("调用失败");
            }
            return ResponseHelper.getSuccessResponse(response.getBody());
        } catch (AlipayApiException e) {
            logger.error(e.getMessage());
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
    }

    //生成商户网站唯一订单号
    private String generateUniqueOrderNo() {
        String rndStr = "KL" + "O" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
        String paymentID = rndStr.substring(0, 32);// 订单ID
        return paymentID;
    }

    //生成快乐号
    private String generateHappyNo() {
        int[] array = {0,1,2,3,4,5,6,7,8,9};
        Random rand = new Random();
        for (int i = 10; i > 1; i--) {
            int index = rand.nextInt(i);
            int tmp = array[index];
            array[index] = array[i - 1];
            array[i - 1] = tmp;
        }
        int result = 0;
        for(int i = 0; i < 6; i++) {
            result = result * 10 + array[i];
        }
        String happyNo = "KL";
        List<String> klNoList = userMapper.selectHappyNoList();
        if (result != 111111 && result != 222222 && result != 333333 && result != 444444 && 
                result != 555555 && result != 666666 && result != 777777 && result != 888888 && result != 999999) {
            happyNo = happyNo + result;;
            if (CollectionUtils.isNotEmpty(klNoList) && !klNoList.contains(happyNo)) { //判断数据库是否存在当前生成的快乐号
                return happyNo;
            } else {
                return generateHappyNo();
            }
        } else {
            return generateHappyNo();
        }
    }

    @Override
    public DataResponse selectUserByHappyNo(String happyNo) {
        UserDTO user = new UserDTO();
        user.setHappyNo(happyNo);
        DataResponse res = null;
        if (StringUtils.isBlank(happyNo)) {
            res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "传入快乐号不能为空");
            return res;
        }
        List<UserDTO> userList = userMapper.selectUserInfo(user);
        if (CollectionUtils.isEmpty(userList)) {
            res = ResponseHelper.getSuccessResponse("isExist", "N");
        } else {
            res = ResponseHelper.getSuccessResponse("isExist", "Y");
        }
        return res;
    }

    @Override
    public DataResponse selectUserByMobilephone(String mobilephone) {
        UserDTO user = new UserDTO();
        user.setMobilephone(mobilephone);
        DataResponse res = null;
        if (StringUtils.isBlank(mobilephone)) {
            res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "传入手机号不能为空");
            return res;
        }
        List<UserDTO> userList = userMapper.selectUserInfo(user);
        if (CollectionUtils.isEmpty(userList)) {
            res = ResponseHelper.getSuccessResponse("isExist", "N");
        } else {
            res = ResponseHelper.getSuccessResponse("isExist", "Y");
        }
        return res;
    }

    @Override
    public DataResponse appAliPayNotify(HttpServletRequest request) {
        System.out.println("----------------阿里服务器消费手机回调-------" + request);
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        DataResponse res = null;
        if (MapUtils.isNotEmpty(requestParams)) {
            for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
                }
                // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
                // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
                params.put(name, valueStr);
            }
            // 商户订单号
            String out_trade_no = "";
            // 支付宝交易号
            String trade_no = "";
            try {
                // 调用SDK验证签名
                boolean flag = AlipaySignature.rsaCheckV1(params, env.getProperty("alipay.public_key"), "UTF-8", "RSA2");
                // 商户订单号
                out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
                // 支付宝交易号
                trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
                // 交易状态
                String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
                String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");
                String info = "flag==" + flag + ";out_trade_no = " + out_trade_no + ";trade_no" + trade_no
                        + ";trade_status = " + trade_status + ";total_amount=" + total_amount;
                logger.info(info);
                if (flag && trade_status.equals("TRADE_SUCCESS")) {
                    // 修改订单状态
                    // 已缴费----开始处理业务
                    OrderDTO orderDTO = orderRepo.findOne(trade_no);
                    orderDTO.setStatus(1);
                    orderDTO.setTradeNo(trade_no);
                    orderRepo.saveAndFlush(orderDTO);
                    res = ResponseHelper.getResponse(MsgStatus.STATUS_OK,"支付成功");
                }
            } catch (Exception e) {
                OrderDTO orderDTO = orderRepo.findOne(trade_no);
                orderDTO.setStatus(-1);
                orderDTO.setTradeNo(trade_no);
                orderRepo.saveAndFlush(orderDTO);
                res = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED,"支付失败");
            }
        }
        return res;
    }

    public static void main(String[] args) {
//        String trade_no0 = "zlnsj" + "O" + UUID.randomUUID().toString().replaceAll("-", "").toLowerCase();
//        System.out.println(trade_no0.length());
//        Map<String,String> param = new HashMap<String,String>();
//        param.put("app_id", "2018071860704436");
//        try {
//            String dsfs = AlipaySignature.rsaSign("2018071860704436", "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCGIB0Cmql/I1Za6Vu87UkasGO50hTTWy4iSbJj99VJ+QCr63pEWOZBUgAICyxL5t4rBuUGQYQfQ0QrbHR/MQnY04csu1vht2dqBsi6DMzr2Rt7pPw/m+TQakIaQIPQfDKjeGbhHUAPp70hsaLIMvWLW6bRlsHQcPbhUmFIAaHgOCfIx2SjYk1UaRHSbo4nrpPatpFqaYhTDkVG1MdPWvlRH4sQRdSQp4+BLkdxKBQ2O05DSw8d/LnemfzLnE4RxHM+gxps5xcB6oLqzdUktvNDKOTCKvEpQUvwBwtllXuyQFyb0acuzLnp1OoRuweMpWqeDkLGzkNqT7Ujpp7uXI6fAgMBAAECggEAAIvi8l7E8AKp2Gb4+7UPxi8PyPMFKLNHZdZdBrE8yjdcfFbSQbMHBR8bZuz8ujZvk0dM6ZCcxC/W+EJR2y7M9nguJc2Bm1LO9gyfBrsEnrVcuk06xduRvBOiv06h+th2sFnOOX6QA0BQsfFyU1R50Z6G+HWfxoSfTN20DcIL8cjnQ9eaAQng9qthzlHIP/qtqii77G75w71K1A61VwgblHHVWpHzVd7TZ1oVXpCORj7QYCVpYQVQOdoIc2dYIlSpawfV2wTRaMeThNUBnFcS8SizOmbtlHWnonBDPQcv/NAwymvuyb8Q0uOSVJVd+MboHwxpfSy2x3EgbyUAkPvd0QKBgQDORZ3RSyThH7epF+JrHOtkNTGqW/OmsZPjdTURv5unDRg36g2VQiHleS7SqUHl8ff2XQZvC93HGqPrt1KEDwAc5UbnLyscm30Y4Z40m9f5X3+k2e7D1IzLZGCcMzucu61doTfA3XODJsGc3yHdMzl3UqmKcd/0g9d/q8AbynY66QKBgQCmdd36SA17BWFfbUeEHBbxevMV4IjeEZpv3ZLdHyNov1FYg+P2nAfMYLME8D2WAgVifAuNcGDeeO0lwRGpuSKKazWZA492eKiS33Q8fLV6JTPnmXauZb0Khf70MPvktx9cWr8XhjkG3YrxAQfaoXLCcEZ7XV2S02JGd3tnWS14RwKBgQC/Sk5eLwrHf+uJ8+11Gj+uEaq6a0Xc++fDVAngKMqHtBwWlob8OXVH4wcqM+85+RjUr1ZtGxsULz9/NOZgM60OHw6PDO41PHlZ3roh3bj/ubGdRsInd/EOGkuB7/1Dj8TqBL24rWYXZZS+DyvPgFa1ssIp8wsXLkFmU/f3jd3xKQKBgCxgwA05qF5j0NHgEHDoDDXU0XnDormRd9ra94x8ALSsTMOMZfoZHvsdzJxEcCbN4yGecHYEv86P7qliD5NwCAVfD6r7iAPNpyOA7zwxAzDNOklEYJ+eAAgOMSpo5L7VE0dL6iYbYpix95jI7Y8b+7xasm+xNIEwWcLvl7a1z6mBAoGAOXI8SZKUAEZhvEuhr1CRM4zV7SPmSAwe01AffxMruRvpOuuvlbym2Y3W9BdSA07nEjIZK/2eB8cRMTKGZ0+j9qIQGKzZz+tnSSZ2JcYpHGXL2jJRcZ6j/MUpFaocRoCuPDk+LHY5clQHmSNgb2n2t97BMoufPsb0TmWCAJ+7HqM=", "UTF-8");
//            System.out.println(dsfs);
//        } catch (AlipayApiException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
        new UserService().registerHuanxin("KT3452543354","tr4rLNcv");
    }

    //获取差异秒数
    private Long getDifferenceSeconds(Date sendTime,Date currDate) {
        Long secondsInterval = currDate.getTime() - sendTime.getTime();
        return secondsInterval;
    }

    //检测是否再次发送短信
    private Boolean checkSendShortMessageAgain(String mobilephone,Map<String,Object> smsMap) {
        Date sendTime = (Date) smsMap.get(mobilephone + "Time");
        if (sendTime == null) {
            return true;
        }
        long intervalMilliSeconds = getDifferenceSeconds(sendTime, new Date());
        long intervalSeconds = intervalMilliSeconds%1000==0?intervalMilliSeconds/1000:intervalMilliSeconds/1000+1;
        long overdueSeconds = Long.valueOf(env.getProperty("app.sms.overdueseconds"));
        if (intervalSeconds > overdueSeconds) {
            return true;
        }
        return false;
    }

    /**
     * 调用微信统一下单接口
     */
    //@Override
    public DataResponse wechatPayOrder(float payAmount, HttpServletRequest request) {
        String appId = WechatPayConfig.WECHAT_APPID;//request.getParameter("appId");
        String openid = WechatPayConfig.WECHAT_APPSECRET;//request.getParameter("openid");
        String mchId = WechatPayConfig.WECHAT_MCHID;//request.getParameter("mchId");
        String apiKey = WechatPayConfig.WECHAT_APPKEY;//request.getParameter("apiKey");
        String unifiedOrder = WechatPayConfig.UNIFIEDORDER_API;
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(mchId)
                || StringUtils.isBlank(apiKey)) {
            logger.info("appId=" + appId + "; openid=" + openid + "; mchId=" + mchId + "; apiKey=" + apiKey);
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "获取请求参数失败");
        }
        SortedMap<String, Object> parameterMap = new TreeMap<String, Object>();
        String outTradeNo = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        parameterMap.put("appid", appId);
        parameterMap.put("attach", "活动付费");
        parameterMap.put("body", "快乐APP活动付费");
        parameterMap.put("mch_id", mchId);
        parameterMap.put("nonce_str", UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32));
        parameterMap.put("notify_url", request.getRequestURL().toString().split("/api/")[0] + wechatNotify);// "http://xxx.com"
        parameterMap.put("out_trade_no", outTradeNo);
        parameterMap.put("spbill_create_ip", request.getRemoteHost());//request.getRemoteAddr()
//        BigDecimal total = totalAmount.multiply(new BigDecimal(100));
        java.text.DecimalFormat df = new java.text.DecimalFormat("0");
        parameterMap.put("total_fee", df.format(payAmount).toString());
        parameterMap.put("trade_type", "APP");
        String sign = CommonUtil.createSign("UTF-8", parameterMap, apiKey);
        parameterMap.put("sign", sign);

        String requestXML = CommonUtil.getRequestXml(parameterMap);
        logger.info(requestXML);
        String result = CommonUtil.httpsRequest(unifiedOrder, "POST", requestXML);
        logger.info(result);
        Map<String, String> map = null;
        SortedMap<String, Object> signParam = new TreeMap<String, Object>();
        try {
            map = CommonUtil.doXMLParse(result);
            String return_code = map.get("return_code");
            String prepay_id = null;
            if (return_code.contains("SUCCESS")) {
                prepay_id = map.get("prepay_id");// 获取到prepay_id
            }
            long currentTimeMillis = System.currentTimeMillis();// 生成时间戳
            long second = currentTimeMillis / 1000L;// （转换成秒）
            String seconds = String.valueOf(second).substring(0, 10); // 截取前10位

            signParam.put("appId", appId);// app_id
            signParam.put("package", "prepay_id=" + prepay_id);// 默认sign=WXPay
            signParam.put("nonceStr", CommonUtil.getRandomString(32));// 自定义不重复的长度不长于32位
            signParam.put("timeStamp", seconds);// 北京时间时间戳
            signParam.put("signType", "MD5");// 北京时间时间戳
            String signAgain = CommonUtil.createSign("UTF-8", signParam, WechatPayConfig.WECHAT_APPKEY);// 再次生成签名
            signParam.put("paySign", signAgain);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseHelper.getResponse(MsgStatus.STATUS_FAILED, "获取请求参数失败");
        }
        return ResponseHelper.getSuccessResponse("paramterMap", signParam);
    }

    @Override
    public DataResponse updateUserPwd(String mobilephone, String oldPwd, String newPwd) {
        UserDTO  user = userRepo.findByMobilephone(mobilephone);
        DataResponse resp = null;
        if (oldPwd.equals(user.getPassword())) {
            user.setPassword(newPwd);
            try {
                userRepo.saveAndFlush(user);
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
            } catch (Exception e) {
                resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
            }
        } else {
            resp = ResponseHelper.getResponse(MsgStatus.PWD_VALID_FAIL, "旧密码输入错误!");
        }
        return resp;
    }

    @Override
    public DataResponse saveUserActivity(String happyNo, long actid) {
        DataResponse resp = null;
        try {
            userMapper.insertUserActivity(happyNo, actid);
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
        } catch (Exception e) {
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }
    
    public UserDTO selectByUserId(Long userId) {
    	return userRepo.getOne(userId);
    }

	@Override
	public UserDTO save(UserDTO user) {
		// TODO Auto-generated method stub
		return userRepo.save(user);
	}

    @Override
    public DataResponse updateUserNickName(long userId, String nickname) {
        DataResponse resp = null;
        try {
            UserDTO userDo = userRepo.findOne(userId);
            logger.info("userId={},nickname={}", userId, nickname);
            userDo.setNickname(nickname);
            userRepo.saveAndFlush(userDo);
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
        } catch (Exception e) {
            logger.info(e.getMessage());
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }

    @Override
    public DataResponse updateUserSignature(long userId, String signature) {
        DataResponse resp = null;
        try {
            UserDTO userDo = userRepo.findOne(userId);
            logger.info("userId={},nickname={}", userId, signature);
            userDo.setNickname(signature);
            userRepo.saveAndFlush(userDo);
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_OK);
        } catch (Exception e) {
            logger.info(e.getMessage());
            resp = ResponseHelper.getResponse(MsgStatus.STATUS_FAILED);
        }
        return resp;
    }

    @Override
    public DataResponse queryUserFriendsInfo(String happyNo) {
        List<UserDTO> friendsList = userMapper.queryUserFriendsInfo(happyNo);
        return null;
    }
}
